package com.improve.frame.common.utils;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description Web工具类
 * @Author wzxing918
 * @Date 2021-03-31
 * @Version 1.0.0
 **/
@UtilityClass
@Slf4j
public final class WebUtil {
    /**
     * 获取本地IP地址
     *
     * @return IP
     */
    public static String getLocalIp() {
        if (isWindows()) {
            try {
                return InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.error("获取本地IP地址异常", e);
            }
        }
        return getLinuxLocalIp();
    }

    /**
     * 判断操作系统是否是Windows
     *
     * @return true/false
     */
    public static boolean isWindows() {
        String osName = System.getProperty("os.name");
        return osName.toLowerCase().contains("windows");
    }

    /**
     * 获取本地Host名称
     *
     * @return Host名称
     */
    public static String getLocalHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            log.error("获取本地Host地址异常", e);
        }
        return null;
    }

    /**
     * 获取Linux下的IP地址
     *
     * @return IP
     */
    private static String getLinuxLocalIp() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface network = en.nextElement();
                String name = network.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = network.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipAddress = inetAddress.getHostAddress();
                            if (!ipAddress.contains("::") && !ipAddress.contains("0:0:") && !ipAddress.contains("fe80")) {
                                ip = ipAddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    /**
     * 是否ajax请求
     *
     * @param request 请求对象
     * @return true/false
     */
    public static boolean isAjax(HttpServletRequest request) {
        return request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest"));
    }

    /**
     * 获取请求路径
     *
     * @param request 请求对象
     * @return 请求路径
     */
    public static String getHostUrl(HttpServletRequest request) {
        StringBuilder buffer = new StringBuilder(request.getScheme() + "://" + request.getServerName());
        int port = 80;
        if (request.getServerPort() != port) {
            buffer.append(":").append(request.getServerPort());
        }
        return buffer.toString();
    }


    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 获取request
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes() != null ? getRequestAttributes().getRequest() : null;
    }

    /**
     * 获取response
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes() != null ? getRequestAttributes().getResponse() : null;
    }

    /**
     * 获取请求IP
     *
     * @return IP
     */
    public static String getRequestIp() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        String unknown = "unknown";
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /**
     * 获取所有请求参数
     *
     * @param request 请求路径
     * @return 请求参数
     */
    public static String getParams(HttpServletRequest request) {
        String param = null;
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                stringBuilder.append(inputStr);
            }
            JSONObject jsonObject = JSON.parseObject(stringBuilder.toString());
            param = jsonObject.toJSONString();
        } catch (Exception e) {
            log.error("获取请求参数异常", e);
        }
        return param;
    }

    /**
     * 获取domain
     *
     * @param request 请求对象
     * @return domain
     */
    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    /**
     * 写出数据
     *
     * @param data 数据内容
     */
    public static void write(@NotNull String data) {
        write(data.getBytes());
    }

    /**
     * 写出数据
     *
     * @param bytes 数据内容
     */
    public static void write(byte[] bytes) {
        HttpServletResponse response = getResponse();
        if (Objects.nonNull(response)) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            write(response, bytes);
        }
    }

    /**
     * 写出数据
     *
     * @param response 响应结果
     */
    public static void write(HttpServletResponse response, byte[] bytes) {
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        try {
            IoUtil.write(response.getOutputStream(), true, bytes);
        } catch (IOException e) {
            log.error("IO异常", e);
        }
    }

    /**
     * 写出图片
     *
     * @param bytes 图片字节数组
     */
    public static void writeImage(byte[] bytes) {
        writeImage(bytes, MediaType.IMAGE_JPEG_VALUE);
    }

    /**
     * 写出数据
     *
     * @param bytes 数据内容
     */
    public static void writeImage(byte[] bytes, String mediaType) {
        HttpServletResponse response = getResponse();
        if (Objects.nonNull(response)) {
            setImageType(response, mediaType);
            write(response, bytes);
        }
    }

    /**
     * 写出图片
     *
     * @param image 图片
     */
    public static void writeImage(BufferedImage image) {
        HttpServletResponse response = getResponse();
        if (Objects.nonNull(response)) {
            try (ServletOutputStream os = getResponse().getOutputStream()) {
                setImageType(response, MediaType.IMAGE_PNG_VALUE);
                ImageIO.write(image, "PNG", os);
                os.flush();
            } catch (IOException e) {
                log.error("IO异常", e);
            }
        }
    }

    /**
     * 设置图片类型
     *
     * @param response  响应结果
     * @param mediaType 图片类型
     */
    private static void setImageType(HttpServletResponse response, String mediaType) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType(mediaType);
    }

    /**
     * 将HttpServletRequest参数转化为Map
     *
     * @param request {HttpServletRequest}
     * @return 转化后的Map
     */
    public static Map<String, String> requestToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>(8);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(entry.getKey(), valueStr);
        }
        return params;
    }
}
